/*系统公共的控件、组件 调用的JS*/
var WIDGET_PATH_PREFIX = ctx + "widget/";

var CN_WIDGET = {
	// 初始化select的值
	initializeSelectVal : function(selId, selVal, selText) {
		var multiple = $('#' + selId).attr("multiple");
		selVal = selVal || $('#' + selId).attr("val");
		selText = selText || $('#' + selId).attr("txt");
		if (selVal != undefined && selVal != "") {
			if (multiple) {// 多选
				var vals = selVal.split(",");
				if(selText) {
					var txts = selText.split(",");
					if (vals.length != txts.length) {
						return;
					}
					for (var i = 0; i < vals.length; i++) {
						if(fiterRepeat(vals[i])){
							var option = $('<option selected="selected" value="' + vals[i] + '" >' + txts[i] + '</option>');
							$('#' + selId).append(option).trigger('change');
						}
					}
				} else {
					$('#' + selId).val(vals).trigger('change');
				}
			} else {
				if(selText) {
					var option = $('<option selected="selected" value="' + selVal + '" >' + selText + '</option>');
					$('#' + selId).append(option).trigger('change');
				} else {
					$('#' + selId).val(selVal).trigger('change');
				}
			}
		}
		//判断是否存在重复的值
		function fiterRepeat(val){
			var result =true;
			if($('#' + selId).find("option").length != 0){
				$('#' + selId).find("option").each(function(){
					if($(this).val()===val)
						result = false;
				});
			}
			return result;
		}
	},
	// 生成自定义下拉
	triggerSelectOnCustom : function(domId, option) {
		var placeholder = '';
		var max = 1;
		var width = '200px';
		if(option) {
			if(option.placeholder) {
				placeholder = option.placeholder;
			}
			if(option.max) {
				max = option.max;
			}
			if(option.width) {
				width = option.width;
			}
		}
		var $domId = $('#' + domId);
		$domId.select2({
			tags : true,
			maximumSelectionLength : max,
			width : width,
			placeholder : placeholder,
			multiple : true,
			cache : false,
			createTag: function (params) {
				var existVal = $domId.val(); 
				var term = $.trim(params.term);
				if(existVal) {
					if($.inArray(term, existVal) != -1) {  // 已经存在这个标签了
						return undefined;
					}
				}
			    if (term === '') {
			      return null;
			    }
			    return {
			    	id: term,
			    	text: term,
			    	newTag: true
			    };
		    }
		});
	},
	initDateCustom : function(domId, type, format) {
		laydate.render({
			elem: '#' + domId,
			type: type,
			format: format
		});
	},
	initDateYMD : function(domId) {
		laydate.render({
			elem: '#' + domId
		});
	},
	initDateYMDHMS : function(domId) {
		CN_WIDGET.initDateCustom(domId, 'datetime', 'yyyy-MM-dd HH:mm:ss');
	}
}